using Microsoft.AspNetCore.Mvc;
using System.IO;

namespace WinAutoUpdate.WebApi.Controllers {
  [ApiController]
  [Route("[controller]")]
  public class DownloadController : ControllerBase {

    /// <summary>
    /// 存放补丁包的目录
    /// </summary>
    private readonly string fPatchDirectory = "C:/KpApp/PatchDirectory"; // 默认补丁包目录

    public DownloadController(IConfiguration aConfiguration) {
      fPatchDirectory = aConfiguration["PatchDirectory"] ?? fPatchDirectory;
    }

    /// <summary>
    /// 下载补丁文件
    /// </summary>
    /// <param name="aPatchFileName">补丁文件名字</param>
    /// <returns></returns>
    /// <remarks>
    /// 这里的参数使用了[FromRoute(Name = "aPatchFileName")]特性，这样我们方法中的参数名称就可以跟路由定义的占位符变量名称不一致了。
    /// 如果不使用[FromRoute(Name)]特性的话，方法的参数名称是必须要和路由中的参数名称保持一致的。
    /// </remarks>
    [HttpGet("patches/{aPatchFileName}")]
    public IActionResult DownloadPatch([FromRoute(Name = "aPatchFileName")] string aPatchFileName) {
      string patchFilePath = Path.Combine(fPatchDirectory, aPatchFileName);

      if (!System.IO.File.Exists(patchFilePath)) {
        return NotFound();
      }

      var bFileStream = new FileStream(patchFilePath, FileMode.Open, FileAccess.Read);
      var bContentType = "application/zip";

      return File(bFileStream, bContentType, aPatchFileName);
    }
  }
}